package com.zhj.bz.algorithm.sort.swap;

import com.zhj.tool.CallBack;
import com.zhj.tool.TimeTools;

import java.util.Arrays;

/**
 * @author zhj
 */
public class QuickSort {

    public static void main(String[] args) {
        int[] arr = {8, 9, 1, 7, 2, 4, 6, 0, 3};
        sort(arr, 0, arr.length-1);
        System.out.println(Arrays.toString(arr));
        int[] bigArr = new int[80000];
        for (int i = 0; i < 80000; i++) {
            bigArr[i] = (int) (Math.random() * 80000);
        }
        System.out.println("快速排序：");
        TimeTools.useTime(new CallBack(){
            //定义execute方法
            public void execute(){
                sort(bigArr, 0, bigArr.length-1);
            }
        });
    }

    public static void sort(int[] arr, int left, int right) {
        int l = left;
        int r = right;
        int pivot = arr[(left + right) / 2];
        int temp;
        while (l < r) {
            while (arr[l] < pivot) {
                l++;
            }
            while (arr[r] > pivot) {
                r--;
            }
            if (l >= r) {
                break;
            }
            temp = arr[l];
            arr[l] = arr[r];
            arr[r] = temp;

            if (arr[l] == pivot) {
                r--;
            }
            if (arr[r] == pivot) {
                l++;
            }
        }
        if ( l == r) {
            l++;
            r--;
        }
        if (left < r) {
            sort(arr, left , r);
        }
        if (right > l) {
            sort(arr, l , right);
        }
    }
}
